﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Data;
using VAdvantage.Localization;
using System.Globalization;
using VAdvantage.Model;
using System.Text;
using VAdvantage.DataBase;
using VAdvantage.DataService;
using VAdvantage.Login;
using System.Threading;
using VAdvantage.Utility;
using VAdvantage.Process;
using VAdvantage.ProcessEngine;
using VAdvantage.Classes;
using System.ComponentModel;


namespace VAdvantage.Framework
{
    public partial class VLogin : UserControl
    {
        /* current selected language of the application */
        VAdvantage.Login.Language m_language = null;
        /**	Connection OK			*/
        private bool _connectionOK = false;
        /* Application UserID */
        private String _user;
        /** Application Password    */
        Ctx _ctx = Utility.Envs.GetContext();

        /* Process the Login */
        private LoginProcess _login = null;

        /**	Combo Active			*/
        private bool _comboActive = false;

        private String txt_NotConnected, txt_NoDatabase, txt_UserPwdError, txt_RoleError, txt_LoggedIn, txt_Verify;

        private String txt_SelectRole, txt_SelectClient, txt_SelectOrg, txt_SelectWarehouse, txt_LoadingPreference, txt_Completed;

        /* stores the password */
        private String _pwd;

        /* Stores Role in Key Name Pair */
        KeyNamePair role = null;
        /* Stores Client in Key Name Pair */
        KeyNamePair client = null;
        /* Stores Org in Key Name Pair */
        KeyNamePair org = null;

        const int COMBO_STATIC_VALUE = 69;

        /* Harwinder */
        public IHost LoginHost { private get; set; }


        public VLogin()
        {
            InitializeComponent();
            loginContainer.Visibility = System.Windows.Visibility.Visible;
            DefaultTab.Visibility = System.Windows.Visibility.Collapsed;
            dtDate.SelectedDate = DateTime.Today;
            int _windowNo = VAdvantage.Utility.Envs.CreateWindowNo(this);
            txtUserName.KeyDown += new KeyEventHandler(txtUserName_KeyDown);
            txtPassword.KeyDown += new KeyEventHandler(txtUserName_KeyDown);
            cmbLanguages.KeyDown += new KeyEventHandler(txtUserName_KeyDown);

            txtUserName.Focus();
            //progress.Visibility = System.Windows.Visibility.Collapsed;
            // Set LayoutRoot's DataContext to specify binding sources for child elements
            //mainContainer.DataContext = _resources;

        }

        void txtUserName_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                FirstStep();
            }
        }


        void FirstStep()
        {
            _user = txtUserName.Text;
            _pwd = txtPassword.Password;

            isbusy = true;

            ThreadPool.QueueUserWorkItem(delegate
            {
                _connectionOK = TryConnection();

                if (_connectionOK)
                {
                    Deployment.Current.Dispatcher.BeginInvoke
           (delegate
           {
               isbusy = true;
               BusyWindow.IsBusy = false || isbusy;
               lblMessage.Text = txt_Verify;
           });


                    Language l = VAdvantage.Login.Language.GetLoginLanguage();
                    l = Utility.Envs.VerifyLanguage(_ctx, l);
                    _ctx.SetContext(Utility.Envs.LANGUAGE, l.GetAD_Language());
                    Msg.GetMsg(_ctx, "0");

                    //	Set Defaults
                    MUser user = MUser.Get(_ctx);
                    MUserPreference preference = user.GetPreference();
                    //String printerName = preference.GetPrinterName();
                    //DataBase.DataStorage.Get().FillList2();


                    Deployment.Current.Dispatcher.BeginInvoke
                            (delegate
                            {
                                //DataBase.DataStorage.Get().FillList1();
                                isbusy = false;
                                lblMessage.Text = "";
                                BusyWindow.IsBusy = false || isbusy;
                                loginContainer.Visibility = System.Windows.Visibility.Collapsed;
                                // blackRect.Visibility = System.Windows.Visibility.Visible;
                                DefaultTab.Visibility = System.Windows.Visibility.Visible;
                                btnLogin.IsEnabled = true;
                                btnLoginNext.Focus();
                                //ComboRoleChanged(); 
                            });
                }
            });
        }

        /// <summary>
        /// Loads the available Languages
        /// </summary>
        private void LoadLanguages()
        {
            try
            {
                string[] names = VAdvantage.Login.Language.GetNames();
                for (int rows = 0; rows <= names.Length - 1; rows++)
                {
                    cmbLanguages.Items.Add(names[rows]);
                }

                cmbLanguages.SelectedIndex = 0;
            }
            catch (IndexOutOfRangeException)
            {

            }

        }

        private void mainContainer_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            Size canvasSize = e.NewSize;
            //Canvas.SetTop(loginContainer, ((canvasSize.Height / 2) - (loginContainer.Height / 2)));
            //Canvas.SetLeft(loginContainer, ((canvasSize.Width / 2) - (loginContainer.Width / 2)));

            //Canvas.SetTop(DefaultTab, ((canvasSize.Height / 2) - (DefaultTab.Height / 2)));
            //Canvas.SetLeft(DefaultTab, ((canvasSize.Width / 2) - (DefaultTab.Width / 2)));

            Canvas.SetTop(loginOuterBox, ((canvasSize.Height / 2) - (loginOuterBox.Height / 2)));
            Canvas.SetLeft(loginOuterBox, ((canvasSize.Width / 2) - (loginOuterBox.Width / 2)));


            //Canvas.SetTop(progress, ((canvasSize.Height / 2) - (progress.Height / 2)));
            //Canvas.SetLeft(progress, ((canvasSize.Width / 2) - (progress.Width / 2)));

            Canvas.SetTop(BusyWindow, ((canvasSize.Height / 2) - (BusyWindow.Height / 2)));
            Canvas.SetLeft(BusyWindow, ((canvasSize.Width / 2) - (BusyWindow.Width / 2)));

        }


        private void cmbLanguages_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            //// Change the culture, and then rebind
            //_manager.CultureChanged += (s, e) => this._resources.UpdateBindings();
            //_manager.CultureChangeFailed += (s, e) => MessageBox.Show(e.Error.Message);
            //_manager.ChangeCulture(new CultureInfo((sender as FrameworkElement).Tag.ToString()));

            string langName = (string)cmbLanguages.SelectedItem;
            VAdvantage.Login.Language language = VAdvantage.Login.Language.GetLanguage(langName);
            VAdvantage.Login.Language.SetLoginLanguage(language);
            m_language = language;

            System.Globalization.CultureInfo culture = language.GetCulture();
            System.Threading.Thread.CurrentThread.CurrentCulture = culture;
            System.Threading.Thread.CurrentThread.CurrentUICulture = culture;
            System.Globalization.CultureInfo ci = System.Globalization.CultureInfo.CurrentUICulture;

            
            lblUserName.Text = language.GetResource("User");
            lblPassword.Text = language.GetResource("Password");
            lblLanguage.Text = language.GetResource("Language");
            btnLogin.Content = language.GetResource("Login");

            lblClient.Text = language.GetResource("Client");
            lblOrg.Text = language.GetResource("Organization");
            lblRole.Text = language.GetResource("Role");
            lblWarehouse.Text = language.GetResource("Warehouse");
            lblDate.Text = language.GetResource("Date");
            btnLoginNext.Content = language.GetResource("Login");
            btnLoginBack.Content = language.GetResource("Back");

            //	txt_Connected = res.getString("Connected");
            txt_NotConnected = language.GetResource("NotConnected");
            txt_NoDatabase = language.GetResource("DatabaseNotFound");
            txt_UserPwdError = language.GetResource("UserPwdError");
            txt_RoleError = language.GetResource("RoleNotFound");
            txt_LoggedIn = language.GetResource("Authorized");
            txt_Verify = language.GetResource("VerifyUserLanguage");

            txt_SelectRole = language.GetResource("SelectRole");
            txt_SelectClient = language.GetResource("SelectClient");
            txt_SelectOrg = language.GetResource("SelectOrg");
            txt_SelectWarehouse = language.GetResource("SelectWarehouse");
            txt_LoadingPreference = language.GetResource("LoadingPreference");
            txt_Completed = language.GetResource("Completed");
            dtDate.DisplayDate = DateTime.Today;


        }




        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            LoadLanguages();
            //InitLogin();
        }

        bool isbusy = false;
        /// <summary>
        /// 	Try to connect.
        /// </summary>
        /// <returns></returns>
        private bool TryConnection()
        {
            Deployment.Current.Dispatcher.BeginInvoke
            (delegate
            {
                BusyWindow.IsBusy = true || isbusy;
                btnLogin.IsEnabled = false;
            });

            _login = new LoginProcess(_ctx);

            KeyNamePair[] roles = _login.GetRoles(_user, _pwd);
            //Deployment.Current.Dispatcher.BeginInvoke(() => handler(ds, true)); 

            if (roles == null || roles.Length == 0)
            {
                Deployment.Current.Dispatcher.BeginInvoke
                (delegate
                {
                    isbusy = false;
                    BusyWindow.IsBusy = false || isbusy;
                    btnLogin.IsEnabled = true;
                    lblMessage.Text = txt_UserPwdError;
                });
                //Deployment.Current.Dispatcher.BeginInvoke(GUIAction);
                //SetStatusMsg(txt_UserPwdError);
                return false;
            }


            KeyNamePair iniValue = null;
            String iniDefault = Ini.GetProperty(Ini.P_ROLE);
            Deployment.Current.Dispatcher.BeginInvoke
                (delegate
                {

                    AddAdditionalItem(cmbRole,  txt_SelectRole, true);
                    for (int i = 0; i < roles.Length; i++)
                    {
                        cmbRole.Items.Add(roles[i]);
                        if (roles[i].GetName().Equals(iniDefault))
                            iniValue = roles[i];
                    }

                    if (iniValue != null)
                        cmbRole.SelectedItem = iniValue;
                    else
                    {
                        if (cmbRole.Items.Count > 0)
                            cmbRole.SelectedIndex = 0;
                    }
                    //cmbRole.SelectedIndex = 0;

                });
            ////  fill roles






            /********************************************************************************************/
            return true;
        }



        private void ComboRoleChanged()
        {
            btnLoginNext.IsEnabled = false;
            //  btnLoginBack.IsEnabled = false;
            AddAdditionalItem(cmbClient, txt_SelectClient, true);
            BusyWindow.IsBusy = true || isbusy;

            if (role == null || _comboActive)
                return;

            KeyNamePair[] clients = null;

            BackgroundWorker bgw = new BackgroundWorker();
            bgw.DoWork += (ov, ev) =>
            {
                if (!role.GetKey().Equals(COMBO_STATIC_VALUE))
                    clients = _login.GetClients(role);
            };

            bgw.RunWorkerCompleted += (ov, ev) =>
            {
                ////  No Clients
                if (clients == null || clients.Length == 0)
                {
                    _comboActive = false;

                    cmbClient.SelectedIndex = 0;
                    //AddAdditionalItem(cmbOrg, Localization.Resources.SelectOrg, true);
                    //AddAdditionalItem(cmbWarehouse, Localization.Resources.SelectWarehouse, true);
                    BusyWindow.IsBusy = false || isbusy;
                    return;
                }

                //  initial client
                KeyNamePair iniValue = null;
                String iniDefault = Ini.GetProperty(Ini.P_CLIENT);

                //  fill clients
                AddAdditionalItem(cmbClient, txt_SelectClient, true);
                for (int i = 0; i < clients.Length; i++)
                {
                    cmbClient.Items.Add(clients[i]);
                    if (clients[i].GetName().Equals(iniDefault))
                        iniValue = clients[i];
                }

                //	fini
                if (iniValue != null)
                    cmbClient.SelectedItem = iniValue;
                else
                {
                    if (cmbClient.Items.Count > 0)
                        cmbClient.SelectedIndex = 0;
                }

                _comboActive = false;
                BusyWindow.IsBusy = false || isbusy;

                //ComboClientChanged();
            };


            bgw.RunWorkerAsync();


        }



        private void btnLogin_Click(object sender, RoutedEventArgs e)
        {

            _user = txtUserName.Text;
            _pwd = txtPassword.Password;
            isbusy = true;
            ThreadPool.QueueUserWorkItem(delegate
            {
                _connectionOK = TryConnection();

                if (_connectionOK)
                {
                    Deployment.Current.Dispatcher.BeginInvoke
               (delegate
               {
                   isbusy = true;
                   BusyWindow.IsBusy = false || isbusy;
                   lblMessage.Text = txt_Verify;
               });




                    Language l = VAdvantage.Login.Language.GetLoginLanguage();
                    l = Utility.Envs.VerifyLanguage(_ctx, l);
                    _ctx.SetContext(Utility.Envs.LANGUAGE, l.GetAD_Language());
                    Msg.GetMsg(_ctx, "0");

                    //	Set Defaults
                    MUser user = MUser.Get(_ctx);
                    MUserPreference preference = user.GetPreference();


                    //String printerName = preference.GetPrinterName();
                    //DataBase.DataStorage.Get().FillList2();

                    Deployment.Current.Dispatcher.BeginInvoke
                             (delegate
                             {
                                 //DataBase.DataStorage.Get().FillList1();
                                 isbusy = false;
                                 BusyWindow.IsBusy = false || isbusy;
                                 lblMessage.Text = "";
                                 loginContainer.Visibility = System.Windows.Visibility.Collapsed;
                                 // blackRect.Visibility = System.Windows.Visibility.Visible;
                                 DefaultTab.Visibility = System.Windows.Visibility.Visible;
                                 btnLogin.IsEnabled = true;
                                 btnLoginNext.Focus();
                                 //ComboRoleChanged(); 
                             });
                }
            });
        }

        private void OnChangeCulture(object sender, SelectionChangedEventArgs e)
        {

        }


        public void GetData(object o1, object o2)
        {

        }

        public void GUIAction()
        {
            DefaultTab.Visibility = System.Windows.Visibility.Visible;
            loginContainer.Visibility = System.Windows.Visibility.Collapsed;
        }

        public void AddRole(Object obj)
        {
            cmbRole.Items.Add(obj);
        }

        private void cmbRole_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (!_comboActive)
            {
                role = (KeyNamePair)cmbRole.SelectedItem;
                ComboRoleChanged();

            }
        }

        private void cmbClient_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            client = (KeyNamePair)cmbClient.SelectedItem;
            ComboClientChanged();
        }

        void AddAdditionalItem(ComboBox cmb, string display, bool isClear)
        {
            if (isClear)
                cmb.Items.Clear();

            cmb.Items.Add(new KeyNamePair(COMBO_STATIC_VALUE, display));
        }

        private void ComboClientChanged()
        {
            btnLoginNext.IsEnabled = false;
            //       btnLoginBack.IsEnabled = false;

            BusyWindow.IsBusy = true;
            AddAdditionalItem(cmbOrg,  txt_SelectOrg, true);

            if (client == null || _comboActive)
                return;

            _comboActive = true;

            KeyNamePair[] orgs = null;

            BackgroundWorker bgw = new BackgroundWorker();
            bgw.DoWork += (ov, ev) =>
            {

                if (!client.GetKey().Equals(COMBO_STATIC_VALUE))
                    orgs = _login.GetOrgs(client);
            };

            bgw.RunWorkerCompleted += (ov, ev) =>
            {
                //  No Orgs
                if (orgs == null || orgs.Length == 0)
                {
                    //SetStatusMsg(txt_RoleError);
                    BusyWindow.IsBusy = false || isbusy;
                    cmbOrg.SelectedIndex = 0;
                    AddAdditionalItem(cmbWarehouse, txt_SelectWarehouse, true);
                    cmbWarehouse.SelectedIndex = 0;
                    _comboActive = false;
                    return;
                }


                //  initial client
                KeyNamePair orgValue = null;
                KeyNamePair orgValue2 = null;
                String iniDefault = Ini.GetProperty(Ini.P_ORG);

                AddAdditionalItem(cmbOrg, txt_SelectOrg, true);
                //  fill orgs
                for (int i = 0; i < orgs.Length; i++)
                {
                    KeyNamePair oo = orgs[i];
                    cmbOrg.Items.Add(oo);
                    if (oo.GetName().Equals(iniDefault) && oo.GetKey() != 0)
                        orgValue = oo;
                    if (orgValue2 == null && oo.GetKey() != 0)
                        orgValue2 = oo;	//	first non-0 org
                }

                //	Non-0 Org exists and last login was with 0
                if (orgValue2 != null && orgValue == null)
                    orgValue = orgValue2;
                //	Last Org
                if (orgValue != null)
                {
                    _comboActive = false;
                    cmbOrg.SelectedItem = orgValue;
                }
                //	Get first Org
                else
                {
                    orgValue = (KeyNamePair)cmbOrg.SelectedItem;
                    if (cmbOrg.Items.Count > 0)
                        cmbOrg.SelectedIndex = 0;
                }

                BusyWindow.IsBusy = false || isbusy;
                _comboActive = false;
            };

            bgw.RunWorkerAsync();
        }

        private void cmbOrg_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            org = (KeyNamePair)cmbOrg.SelectedItem;
            ComboOrgChanged();

        }	//	ComboClientChanged


        private void ComboOrgChanged()
        {
            btnLoginNext.IsEnabled = false;
            //   btnLoginBack.IsEnabled = false;

            AddAdditionalItem(cmbWarehouse, txt_SelectWarehouse, true);

            if (org == null || _comboActive)
            {
                cmbWarehouse.SelectedIndex = 0;
                return;
            }


            _comboActive = true;
            //
            KeyNamePair[] whs = null;

            BackgroundWorker bgw = new BackgroundWorker();
            bgw.DoWork += (ov, ev) =>
            {
                if (!org.Equals(COMBO_STATIC_VALUE))
                    whs = _login.GetWarehouses(org);
            };

            bgw.RunWorkerCompleted += (ov, ev) =>
            {
                if (whs == null || whs.Length == 0)
                {
                    //SetStatusMsg(txt_RoleError);
                    BusyWindow.IsBusy = false || isbusy;
                    cmbWarehouse.SelectedIndex = 0;
                    if (cmbOrg.SelectedIndex > 0)
                    {
                        btnLoginNext.IsEnabled = true;
                        btnLoginBack.IsEnabled = true;
                    }
                    _comboActive = false;
                    return;
                }

                try
                {
                    BusyWindow.IsBusy = true;
                    if (cmbWarehouse.Items.Count > 0)
                        cmbWarehouse.Items.Clear();
                }
                catch
                {
                }

                //  fill warehouses
                if (whs != null)
                {
                    //  initial warehouse
                    KeyNamePair iniValue = null;
                    String iniDefault = Ini.GetProperty(Ini.P_WAREHOUSE);

                    AddAdditionalItem(cmbWarehouse, txt_SelectWarehouse, true);
                    for (int i = 0; i < whs.Length; i++)
                    {
                        cmbWarehouse.Items.Add(whs[i]);
                        if (whs[i].GetName().Equals(iniDefault))
                            iniValue = whs[i];
                    }

                    if (iniValue != null)
                        cmbWarehouse.SelectedItem = iniValue;
                    else
                    {
                        if (cmbWarehouse.Items.Count > 0)
                            cmbWarehouse.SelectedIndex = 0;
                    }

                    btnLoginNext.IsEnabled = true;
                    btnLoginBack.IsEnabled = true;

                }



                BusyWindow.IsBusy = false || isbusy;
                _comboActive = false;
            };

            bgw.RunWorkerAsync();

        }

        private void cmbWarehouse_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            //return;
        }

        private void btnLoginNext_Click(object sender, RoutedEventArgs e)
        {

            if (cmbRole.SelectedIndex == 0)
            {
                ShowMessage.Error( txt_SelectRole, true);
                return;
            }
            else if (cmbClient.SelectedIndex == 0)
            {
                ShowMessage.Error(txt_SelectClient, true);
                return;
            }
            else if (cmbOrg.SelectedIndex == 0)
            {
                ShowMessage.Error(txt_SelectOrg, true);
                return;
            }

            lblMessage2.Text = txt_LoadingPreference;

            Ini.SetProperty(Ini.P_UID, _user);
            Ini.SetProperty(Ini.P_PWD, _pwd);
            Ini.SetProperty(Ini.P_LANGUAGE, m_language.GetName());


            this.Cursor = Cursors.Wait;
            this.btnLoginNext.IsEnabled = false;
            this.btnLoginBack.IsEnabled = false;
            //LoadPreferenceInfo();

            KeyNamePair ware = (KeyNamePair)cmbWarehouse.SelectedItem;
            DateTime dtTime = (DateTime)dtDate.DisplayDate;
            String printText = "print"; // "cmbPrinter.Text

            if (LoginHost != null)
            {
                //LocalStorageManager.StorageManager.CheckSaveDataLocal();
                DataStorage.GetLookupInfoCache();
                DataStorage.FillWorkFlowCache();
            }

            BackgroundWorker bgw = new BackgroundWorker();

            bgw.DoWork += (sd, ed) =>
            {
                //Msg.GetElement(_ctx, "AD_Client_ID");
                ed.Result = _login.LoadPreferences(org, ware, dtTime, printText);
            };

            bgw.RunWorkerCompleted += (sc, ec) =>
            {
                _login.LoadPreferenceInfo();
                if (ec.Result != null && ec.Result.ToString().Length > 0)
                {
                    ShowMessage.Info(ec.Result.ToString(), true, "", "");
                }
                lblMessage2.Text = txt_Completed;

                if (LoginHost != null)
                {
                    LoginHost.OnLoginCompleted();
                }
                this.Cursor = Cursors.Arrow;
            };
            bgw.RunWorkerAsync();
        }

        public void DoLogin()
        {
            KeyNamePair ware = (KeyNamePair)cmbWarehouse.SelectedItem;
            DateTime dtTime = (DateTime)dtDate.DisplayDate;
            String printText = "print"; // "cmbPrinter.Text
            BackgroundWorker bgw = new BackgroundWorker();

            bgw.DoWork += (sd, ed) =>
            {
                ed.Result = _login.LoadPreferences(org, ware, dtTime, printText);
            };

            bgw.RunWorkerCompleted += (sc, ec) =>
            {
                _login.LoadPreferenceInfo();
                if (ec.Result != null && ec.Result.ToString().Length > 0)
                {
                    ShowMessage.Info(ec.Result.ToString(), true, "", "");
                }
                lblMessage2.Text = txt_Completed;

                if (LoginHost != null)
                {
                    LoginHost.OnLoginCompleted();
                }
                this.Cursor = Cursors.Arrow;
            };
            bgw.RunWorkerAsync();
        }



        public bool InitLogin()
        {
            txtUserName.Text = GlobalVariable.UserName; //Ini.GetProperty(Ini.P_UID);
            txtPassword.Password = GlobalVariable.Pwd; // Ini.GetProperty(Ini.P_PWD);
            cmbLanguages.SelectedItem = Ini.GetProperty(Ini.P_LANGUAGE);
            return true;
        }

        private void Grid_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            e.Handled = true;
        }

        private void btnLoginBack_Click(object sender, RoutedEventArgs e)
        {
            DefaultTab.Visibility = System.Windows.Visibility.Collapsed;
            loginContainer.Visibility = System.Windows.Visibility.Visible;
            //lblMessage.Text = "";
        }

    }
}


